<template>
  <div class="user-center">
    <!-- 用户信息表单 -->
    <el-form :model="user" label-width="100px" class="user-form">
      <el-form-item label="用户账号">
        <el-input v-model="user.username" disabled />
      </el-form-item>
      <el-form-item label="用户昵称">
        <el-input v-model="user.nickname" />
      </el-form-item>
      <el-form-item label="用户电话">
        <el-input v-model="user.phone" />
      </el-form-item>
      <el-form-item label="用户邮箱">
        <el-input v-model="user.email" disabled/>
      </el-form-item>
      <el-form-item label="用户图像">
        <el-upload
            class="avatar-uploader"
            drag
            action="https://run.mocky.io/v3/9d059bf9-4660-45f2-925d-ce80ad6c4d15"
            multiple
            :show-file-list="false"
            :http-request="toUploadFile"
        >
          <el-avatar :size="100" :src="user.headIcon" />
        </el-upload>
      </el-form-item>
    </el-form>

    <!-- 底部按钮 -->
    <div class="action-buttons">
      <el-button @click="cancel">返回</el-button>
      <el-button type="primary" @click="updateUserInfo(user)">确定</el-button>
    </div>

    <!-- 修改密码按钮 -->
    <div class="change-password-button">
      <el-button type="text" @click="openChangePasswordDialog">修改密码</el-button>
    </div>

    <!-- 修改密码弹框 -->
    <el-dialog v-model="changePasswordDialogVisible" title="修改密码" width="30%">
      <el-form :model="passwordForm" label-width="100px">
        <el-form-item label="新密码">
          <el-input v-model="passwordForm.password" type="password" />
        </el-form-item>
        <el-form-item label="确认新密码">
          <el-input v-model="passwordForm.passwordAgain" type="password" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="user.email" disabled/>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="passwordForm.registerCode" />
          <el-button type="primary" @click="sendVerificationCode(user.email)">发送验证码</el-button>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="changePasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="changePassword(passwordForm)">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, reactive, ref} from 'vue';
import { ElMessage } from 'element-plus';
import {useRoute, useRouter} from "vue-router"
import userAPI from "@/api/module/user";
import famousAPI from "@/api/module/file";

const changePasswordDialogVisible = ref(false);
const user = reactive({});

const route = useRoute()
const router = useRouter();

onMounted(() => {
  let id = route.query.id;
  getUserDetail(id);
})

const getUserDetail =  async (id) => {
  await userAPI.detail(id).then(res => {
    user.id = res.data.id;
    user.username = res.data.username;
    user.nickname = res.data.nickname;
    user.phone = res.data.phone;
    user.email = res.data.email;
    user.headIcon = res.data.headIcon;
  }).catch((err) => {
    console.log(err)
  });
}

const passwordForm = ref({
  username: "",
  password: '',
  passwordAgain: '',
  email: '',
  registerCode: '',
});


const cancel = () => {
  router.push({
    path:'/index',
  });
};

const updateUserInfo = async (user) => {
  await userAPI.update(user).then(res => {
    if (res.code === 200) {
      ElMessage({
        message: '修改成功',
        type: 'success',
      })
      let id = route.query.id;
      getUserDetail(id);
    } else {
      ElMessage.error(res.msg);
    }
  })
};

//上传文件
const toUploadFile = async (param) => {
  console.log(param);
  const file = param.file;
  const formData = new FormData();
  formData.append('file', file);
  await famousAPI.add(formData).then((res) => {
    ElMessage.success("上传成功")
    if (res.code === 200) {
      let data = res.data
      let {fileUrl} = data
      user.headIcon = fileUrl ? 'http://localhost:18000/course/famous/preview/' + fileUrl : null
    } else {
      ElMessage.error(res.msg);
    }
  })
}

const openChangePasswordDialog = () => {
  changePasswordDialogVisible.value = true;
};

const sendVerificationCode = async (email) => {
  await userAPI.sendEmail(email).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        message: '验证码已发送',
        type: 'success',
      })
    } else {
      ElMessage.error(res.data.msg);
    }
  })
};

const changePassword = async (passwordForm) => {
  passwordForm.username = user.username;
  passwordForm.email = user.email;
  await userAPI.uploadPassword(passwordForm).then(res => {
    if (res.data.code === 200) {
      ElMessage({
        message: '密码修改成功',
        type: 'success',
      })
    } else {
      ElMessage.error(res.data.msg);
    }
  })
};
</script>

<style scoped>
.user-center {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.user-form {
  margin-top: 20px;
}

.action-buttons {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.change-password-button {
  text-align: center;
  margin-top: 20px;
}

.el-avatar {
  cursor: pointer;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>